import axios from 'axios';
import  type {AxiosResponse,AxiosRequestConfig} from 'axios';

// import store from '@/utils/store.js';
import { ElMessage } from 'element-plus'


//做个性化定制， 
const service  = axios.create({
  baseURL: 'http://localhost:8080',
  timeout: 10000,
});

//配置 service 在每次请求的时候 携带这个token
service.interceptors.request.use(config=>{

  //请求的时候携带token
//   const token = store.state.token;
//   if(token){
//     config.headers['Authentication'] = token
//   }


  return config;
})


service.interceptors.response.use((response:AxiosResponse)=> {

    if(response.status == 200){ //http 状态
        const res = response.data
        const {code,msg,data} = res;
        if(code == 200){
            return data  //真实的数据
        }else if(code == 404){
            ElMessage({ message: '请求路径不正确', type: 'error'})
            return Promise.reject('error')
        }else if(code == 500){
            ElMessage({ message: msg||'请求接口出错...', type: 'error'})
            return Promise.reject('error')
        } else if(code == 403){
            ElMessage({ message: '接口权限异常，请授权', type: 'error'})
            return Promise.reject('error')
        } else if(code == 401){  //token失效了
            ElMessage({ message: '登录超时,需要重新登录', type: 'error'})
            return Promise.reject('error')
            //重新登录
            //跳转到登录画面
        } 


    }else{ //前段
        ElMessage({ message: '请求异常', type: 'error'})
        return Promise.reject('error')
    }

})




// export default service;


const http = {
        //get请求
        get<T = any>(url: string, config?: AxiosRequestConfig): Promise<T>{
            return service.get(url,config);
        },

        //post请求
        post<T = any>(url: string, data?: object, config?: AxiosRequestConfig): Promise<T>{
            return service.post(url,data,config);
        }

}

export default http